package com.appstore.service.impl;

import com.appstore.mapper.AppCommentMapper;
import com.appstore.mapper.AppMapper;
import com.appstore.domain.entity.AppComment;
import com.appstore.service.AppCommentService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AppCommentServiceImpl implements AppCommentService {

    @Resource
    private AppCommentMapper appCommentMapper;

    @Resource
    private AppMapper appMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addAppComment(AppComment appComment) {

        int add = appCommentMapper.addAppComment(appComment);
        if(add <= 0 ) return 0;

        return updateAppRating(appComment.getAppId());
    }

    @Override
    public int deleteAppComment(Long id) {
        AppComment appComment = appCommentMapper.getAppComment(id);
        int delete = appCommentMapper.deleteAppComment(id);
        if(delete <= 0 ) return 0;
        return updateAppRating(appComment.getAppId());
    }

    @Override
    public AppComment getAppComment(Long id) {
        return appCommentMapper.getAppComment(id);
    }

    @Override
    public List<AppComment> getAppCommentListByAppId(Long appId) {
        return appCommentMapper.getAppCommentListByAppId(appId);
    }

    //更新app评分
    private int updateAppRating(Long id){

        Double ratingCount = 0.0;
        List<AppComment> appCommentList = appCommentMapper.getAppCommentListByAppId(id);
        for (AppComment comment : appCommentList) {
            ratingCount += comment.getRating();
        }
        Double rating = ratingCount / appCommentList.size();
        return appMapper.updateRating(id,rating);
    }
}
